import { onBeforeUnmount, onMounted, ref } from 'vue'
import { common } from '/@src/api'
import { Tooltip, selectCursor, defaultCursor } from '/@src/utils'
import { CascaderValue, ElMessage } from 'element-plus'
import { flattenDeep } from 'lodash'
import { supermapReady } from '/@packages/components'

export default function () {
  const { $myapp } = supermapReady()
  onMounted(async () => {
    // 初始化加载北京行政区数据
    const res: any = await common.get('./datas/Beijing.json')
    const root = {
      label: '北京市',
      value: '1',
      children: []
    }
    if (res && res.features) {
      res.features.forEach((feature) => {
        root.children.push({
          label: feature.properties.name,
          value: '1-' + root.children.length,
          points: flattenDeep(feature.geometry.coordinates)
        })
      })
      cascaderDatas.value = [].concat([root])
    } else {
      ElMessage.warning('获取行政区数据失败', res)
    }
  })
  onBeforeUnmount(() => {
    clearClip()
  })
  // 级联选择的数据
  const cascaderDatas = ref([])
  const selectArea = ref()
  // 级联属性设置
  const cascaderProps = {
    // multiple: true
  }
  // 行政区面
  let regionEntity = null
  // 选择行政区改变事件
  const onChange = (value: CascaderValue) => {
    const node = cascaderDatas.value[0].children.find(
      (item) => item.value === value[1]
    )
    clearClip()
    if (node) {
      clipLayer(node.points)
      addEntity(node.points)
      $myapp.viewer.zoomTo(regionEntity)
    }
  }
  // 点击清空按钮事件
  const onClear = () => {
    clearClip()
  }
  // 裁剪所有模型图层
  const clipLayer = (pts) => {
    const modifyPts = []
    pts.forEach((item, index) => {
      modifyPts.push(item)
      if ((index + 1) % 2 === 0) {
        modifyPts.push(0)
      }
    })
    // 遍历图层设置
    $myapp.viewer.scene.layers.layerQueue.forEach((layer) => {
      layer.clearDataRequestRegions()
      layer.setDataRequestRegions([pts])
      layer.setModifyRegions(
        [modifyPts],
        SuperMap3D.ModifyRegionMode.CLIP_OUTSIDE
      )
    })
  }
  // 清楚请求范围并清除显示的实体对象
  const clearClip = () => {
    $myapp.viewer.scene.layers.layerQueue.forEach((layer) => {
      layer.clearDataRequestRegions()
      layer.clearModifyRegions()
    })
    if (regionEntity) {
      $myapp.viewer.entities.remove(regionEntity)
      regionEntity = null
    }
  }
  // 绘制自定义区域
  const onDrawPolygon = () => {
    const tooltop = new Tooltip('绘制区域', $myapp.viewer.canvas.parentElement)
    selectCursor($myapp.viewer)
    const handler = new SuperMap3D.DrawHandler(
      $myapp.viewer,
      SuperMap3D.DrawMode.Polygon,
      SuperMap3D.ClampMode.Space
    )
    handler.drawEvt.addEventListener((result) => {
      const pts = []
      const positions = [...result.object.positions]
      if (positions.length > 2) {
        positions.forEach((point) => {
          const cartographic = SuperMap3D.Cartographic.fromCartesian(point)
          const longitude = SuperMap3D.Math.toDegrees(cartographic.longitude)
          const latitude = SuperMap3D.Math.toDegrees(cartographic.latitude)
          pts.push(longitude)
          pts.push(latitude)
        })
        clipLayer(pts)
        addEntity(pts)
        handler.deactivate()
        handler.clear()
        defaultCursor($myapp.viewer)
        tooltop.destroy()
      } else {
        ElMessage.warning('请绘制超过三个点的多边形')
        handler.activate()
      }
    })
    handler.movingEvt.addEventListener((e) => {
      tooltop.changePosition(e)
    })
    handler.activate()
  }
  // 通过坐标点添加实体对象
  const addEntity = (pts) => {
    const polylinePts = [].concat([...pts], [pts[0], pts[1]])

    regionEntity = $myapp.viewer.entities.add({
      polygon: {
        hierarchy: SuperMap3D.Cartesian3.fromDegreesArray(pts),
        material: SuperMap3D.Color.RED.withAlpha(0.5),
        classificationType: SuperMap3D.ClassificationType.TERRAIN
      },
      polyline: {
        positions: SuperMap3D.Cartesian3.fromDegreesArray(polylinePts),
        material: SuperMap3D.Color.YELLOW,
        classificationType: SuperMap3D.ClassificationType.TERRAIN,
        clampToGround: true,
        width: 3
      }
    })
  }
  // 清除结果
  const onClearAll = () => {
    selectArea.value = []
    clearClip()
  }
  return {
    cascaderDatas,
    selectArea,
    cascaderProps,
    onChange,
    onClear,
    onClearAll,
    onDrawPolygon
  }
}
